<?php

namespace plugin\ycMassage\utils;

use app\common\manager\SettingsMgr;
use \Exception;
use GuzzleHttp\Client;

class AMap
{
    private $baseURL='https://restapi.amap.com/v3/';
    private $config;
    public function __construct($appid)
    {
        $this->config = SettingsMgr::getChildren($appid, 'map');
        if(!isset($this->config['amap_service_key'])){
            throw new Exception('高德地图服务KEY未配置');
        }
        if(!$this->config['amap_service_key']){
            throw new Exception('高德地图服务KEY未配置');
        }
    }
    public function regeo($options=[])
    {
        $params=[
            'key'=>$this->config['amap_service_key']
        ];
        $params=array_merge($params,$options);
        $client = new Client([
            'base_uri' => $this->baseURL
        ]);
        $response = $client->request('GET', 'geocode/regeo', [
            'query' => $params
        ]);
        $body = $response->getBody();
        $content = $body->getContents();
        if($response->getStatusCode()!=200){
            throw new Exception($content);
        }
        if($content){
            $data = json_decode($content, true);
            if($data['status']!=1){
                throw new Exception($data['info']);
            }
            return $data['regeocode'];
        }
        throw new Exception('请求失败');
    }
    public function geo($options=[])
    {
        $params=[
            'key'=>$this->config['amap_service_key']
        ];
        $params=array_merge($params,$options);
        $client = new Client([
            'base_uri' => $this->baseURL
        ]);
        $response = $client->request('GET', 'geocode/geo', [
            'query' => $params
        ]);
        $body = $response->getBody();
        $content = $body->getContents();
        if($response->getStatusCode()!=200){
            throw new Exception($content);
        }
        if($content){
            $data = json_decode($content, true);
            if($data['status']!=1){
                throw new Exception($data['info']);
            }
            if(empty($data['geocodes'])){
                throw new Exception('获取位置失败');
            }
            return $data['geocodes'][0];
        }
        throw new Exception('请求失败');
    }
}